package com.hosever.biz.controller;

import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.hosever.core.AbstractController;
import com.hosever.model.Tag;
import com.hosever.service.TagService;
import com.hosever.utils.SeverStringUtils;

@Controller
@RequestMapping("/biz/tag")
public class TagControllerBiz extends
		AbstractController<Tag, TagService> {
	
	
	@RequestMapping()
	public String redirect(Model model){
		return "redirect:"+getRelativePath("/list");
	}
	
	/**
	 * 标签管理
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String tagManager(Model model){
		model.addAttribute("nav","tagManager");
		List<Tag> tags = this.service.list();
		model.addAttribute("tags", tags);
		return getRelativePath("/formList");
	}
	
	@RequestMapping(value="/add" ,method = RequestMethod.POST)
	public String tagAdd(Model model,@RequestParam("name")String name,@RequestParam("parentId")String parentId){
		if(SeverStringUtils.isBlank(name)){
			return "redirect:"+getRelativePath("/list");
		}
		Tag tag = new Tag();
		tag.setName(name);
		if(!SeverStringUtils.isBlank(parentId)){
			Tag parentTag = this.service.findById(parentId);
			parentTag.getChildTags().add(tag);
			tag.setParentTag(parentTag);
		}
		this.service.save(tag);
		return "redirect:"+getRelativePath("/list");
	}
	
	@RequestMapping(value="/edit" ,method = RequestMethod.POST)
	public String tagEdit(Model model,@RequestParam("name")String name,@RequestParam("id")String id){
		if(SeverStringUtils.isBlank(name)){
			return "redirect:"+getRelativePath("/list");
		}
		Tag tag = this.service.findById(id);
		tag.setName(name);
		this.service.update(tag);
		return "redirect:"+getRelativePath("/list");
	}
	
	@RequestMapping(value="/del/{id}" ,method = RequestMethod.GET)
	public String tagDel(Model model,@PathVariable("id")String id){
		this.service.del(this.service.findById(id));
		return "redirect:"+getRelativePath("/list");
	}
}
